#include "uart.h"
#define REC_BUF_SIZE 32

static char xdata rec_buff[REC_BUF_SIZE];
static uint8_t xdata current_rec_size = 0;

void uart1Init(uint32_t rate) // 115200bps@11.0592MHz
{
    // timing 1/rate seconds=1/rate*1000,000 us
    uint16_t time = 65536 - 11059200 / 4 / rate;

    SCON = 0x50;  // 8位数据,可变波特率
    AUXR |= 0x01; // 串口1选择定时器2为波特率发生器
    AUXR |= 0x04; // 定时器时钟1T模式
    T2L = time & 0xFF;
    T2H = (time >> 8) & 0xFF; // 设置定时初始值
    AUXR |= 0x10;             // 定时器2开始计时

    ES = 1;
    // 使能串口中断
    EA = 1;
}

void UART1_Isr() interrupt 4
{
    if (TI)
    {
        TI = 0;
    }
    if (RI)
    {
        rec_buff[current_rec_size++] = SBUF;
        RI = 0;
    }
}

void uart1SendByte(uint8_t byte)
{
    SBUF = byte;
    while (TI == 0)
        ;
}
void uart1SendArray(uint8_t *array, uint8_t len)
{
    uint8_t i;
    for (i = 0; i < len; i++)
    {
        uart1SendByte(array[i]);
    }
}
void uart1SendString(char *str)
{
    while (*str != '\0')
    {
        uart1SendByte(*str);
        str++;
    }
}
char *recFromUart1(uint8_t *size)
{
    *size = current_rec_size;
    current_rec_size = 0;
    return rec_buff;
}

bool isUart1SendAvailable()
{
    return current_rec_size != 0;
}

void uart1SendNum(int16_t num)
{
    char num_str[5]; // 65536
    uint8_t l = 0;
    uint8_t i = 0;
    char tmp;
    do
    {
        num_str[l++] = num % 10 + '0';
        num /= 10;
    } while (num);

    for (i = 0; i < l / 2; i++)
    {
        tmp = num_str[i];
        num_str[i] = num_str[l - i - 1];
        num_str[l - i - 1] = tmp;
    }

    uart1SendArray(num_str, l);
}
